<?php
// +----------------------------------------------------------------------
// | najing [ 通用后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.najingquan.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 救火队队长
// +----------------------------------------------------------------------

namespace app\common\model;

use think\facade\Db;
use think\model\concern\SoftDelete;
use think\Validate;
use app\common\model\ManageLog;

class Manage extends Common
{

    const TYPE_SUPER_ID = 1;        //超级管理员 id

    const STATUS_NORMAL = 1;        //用户状态 正常
    const STATUS_DISABLE = 2;       //用户状态 停用

    protected $rule = [
        'username' => 'length:3,20|alphaDash',
        'mobile'   => ['regex' => '^1[3|4|5|6|7|8][0-9]\d{4,8}$'],
        'nickname' => 'length:2,50',
    ];
    protected $msg = [
        'username.length'    => '用户名长度6~20位',
        'username.alphaDash' => '用户名只能是字母、数字或下划线组成',
        'mobile'             => '请输入一个合法的手机号码',
        'nickname'           => '昵称长度为2-50个字符',
    ];


    /**
     * 返回layui的table所需要的格式
     * @author 救火队队长
     * @param $post
     * @return mixed
     */
    public function tableData($post)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = config('paginate.list_rows');
        }

        $list = $this
            ->field('m.*,group_concat(mr.name) as role_name')
            ->alias('m')
            ->leftJoin('manage_role_rel mrr', 'mrr.manage_id = m.id')
            ->leftJoin('manage_role mr', 'mr.id = mrr.role_id')
            ->where('m.id', '<>', $this::TYPE_SUPER_ID)
            ->group("m.id")
            ->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code']  = 0;
        $re['msg']   = '';
        $re['count'] = $list->total();
        $re['data']  = $data;

        return $re;
    }


    /**
     * 注册添加用户
     * @author 救火队队长
     */
    public function toAdd($data)
    {
        $result = array(
            'status' => false,
            'data'   => '',
            'msg'    => ''
        );

        //校验数据
        $validate = new Validate($this->rule, $this->msg);
        if (!$validate->check($data)) {
            $result['msg'] = $validate->getError();
            return $result;
        }


        //判断是新增还是修改
        if (isset($data['id'])) {
            $manageInfo = $this->where(['id' => $data['id']])->find();
            if (!$manageInfo) {
                return error_code(11010);
            }

            if (isset($data['password']) && !empty($data['password'])) {
                if (strlen($data['password']) <= 5 || strlen($data['password']) > 16) {
                    return error_code(11009);
                } else {
                    $data['password'] = $this->enPassword($data['password'], $manageInfo['ctime']);
                }
            } else {
                unset($data['password']);
            }

            unset($data['username']);       //不允许修改用户名
            //更新数据库
            $this->update($data, ['id' => $data['id']]);
        } else {
            //判断用户名是否重复
            $manageInfo = $this->where(['username' => $data['username']])->find();
            if ($manageInfo) {
                return error_code(11011);
            }
            $data['ctime'] = time();

            if (!isset($data['password'][5]) || isset($data['password'][16])) {
                return error_code(11009);
            }
            $data['password'] = $this->enPassword($data['password'], $data['ctime']);
            //插入数据库
            $this->data($data)->save();
            $data['id'] = $this->id;
        }
        //设置角色
        $manageRoleRelModel = new ManageRoleRel();
        //清空所有的旧角色
        $manageRoleRelModel->where(['manage_id' => $data['id']])->delete();

        if (isset($data['role_id'])) {
            $data1 = [];
            foreach ($data['role_id'] as $k => $v) {
                $row['manage_id'] = $data['id'];
                $row['role_id']   = $k;
                $data1[]          = $row;
            }
            $manageRoleRelModel->saveAll($data1);
        }


        $result['status'] = true;
        return $result;
    }

    /**
     * 管理员登陆
     * @author 救火队队长
     */
    public function toLogin($data)
    {
        $result = array(
            'status' => false,
            'data'   => '',
            'msg'    => ''
        );
        if (!isset($data['username']) || !isset($data['password'])) {
            $result['msg'] = lang('input user and pwd');
            return $result;
        }

        //校验验证码
        if (isset($data['captcha'])) {
            if (!captcha_check($data['captcha'])) {
                $result['msg'] = lang('captcha error');
                return $result;
            }
        }

        $userInfo = $this->where(array('username' => $data['username']))->find();
        if (!$userInfo) {
            $result['msg'] = lang('account no found');
            return $result;
        }

        //判断账号状态
        if ($userInfo->status != self::STATUS_NORMAL) {
            $result['msg'] = lang('account ice');
            return $result;
        }

        //判断是否是用户名登陆
        $userInfo = $this->where(array('username' => $data['username'], 'password' => $this->enPassword($data['password'], $userInfo->ctime)))->find();
        if ($userInfo) {
            $result = $this->setSession($userInfo);
        } else {
            //写失败次数到session里
            if (session('?manage_login_fail_num')) {
                session('manage_login_fail_num', session('manage_login_fail_num') + 1);
            } else {
                session('manage_login_fail_num', 1);
            }

            $result['msg'] = lang('pwd error');
        }
        return $result;

    }

    /**
     * 管理员修改密码
     * @author 救火队队长
     */
    public function chengePwd($manage_id, $oldPassword, $newPassword)
    {
        $result = [
            'status' => false,
            'data'   => '',
            'msg'    => ''
        ];
        $info   = $this->where(['id' => $manage_id])->find();
        if (!$info) {
            $result['msg'] = "没有找到此账号";
            return $result;
        }
        if ($oldPassword == $newPassword) {
            $result['msg'] = "新密码和旧密码一致";
            return $result;
        }

        if ($info['password'] != $this->enPassword($oldPassword, $info['ctime'])) {
            $result['msg'] = "旧密码不正确";
            return $result;
        }

        $re = $this->update(['password' => $this->enPassword($newPassword, $info['ctime'])], ['id' => $info['id']]);
        if ($re) {
            $result['status'] = true;
            $result['msg']    = "修改成功";
        } else {
            return $result['msg'] = "更新失败";
        }
        return $result;


    }

    /**
     * 设置保存登陆用户信息
     * @author 救火队队长
     */
    private function setSession($userInfo)
    {
        $result = [
            'status' => false,
            'data'   => '',
            'msg'    => ''
        ];
        session('manage', $userInfo->toArray());

        $ips      = $userInfo['ips'];
        $id       = $userInfo['id'];

        $current_ip = ip();
        $end_ip = $current_ip;
        if(!empty($ips)){
            $ip_array = explode(',' , $ips);
            if(!in_array($current_ip,$ip_array)){
                array_push($ip_array , $current_ip);
                $end_ip   = join(',' , $ip_array);
            }
        }
        Db::name('manage')->where(['id'=>$id])->update(['ips'=>$end_ip]);

        $userLogModel = new ManageLog();
        $userLogModel->saveManageLog([
            'manage_id' => session('manage.id'),
            'desc'      => 'manage login',
            'content'   => ''
        ]);

        $result['status'] = true;
        return $result;
    }

    /**
     * 密码加密方法
     * @author 救火队队长
     */
    private function enPassword($password, $ctime)
    {
        return md5(md5($password) . $ctime);
    }

    public function changeBalance($data)
    {
        $manage_id_login    = $data['manage_id_login'];
        $manage_id          = $data['manage_id'];
        $remark             = $data['remark'];
        $money              = $data['money'];
        $money_abs          = abs($money);

        $user_name       = $data['username'];
        $current_balance = $data['balance'];

        if($money >0){
            $result_balance = $current_balance + $money_abs;
        }else{
            $result_balance = $current_balance - $money_abs;
        }
        $blog = true;
        Db::startTrans();
        try{
            $ctime = getUtcTime();
            $desc  = 'Manager ' . (($money >0)? 'Deposit':'Deduct');
            Db::name('manage')->where(['id'=>$manage_id])->update(['balance'=>$result_balance]);
            //记录钱包记录
            Db::name('manage_fund_log')->save([
                'type'          => ($money >0) ? 0 : 1, //类型 0,Credit|1,Debit
                'amount'        => $money_abs,
                'manage_id'     => $manage_id,
                'manage_id_action'=>$manage_id_login, //管理员操作人
                'balance'       => $result_balance,
                'remark'        => !empty($remark)?$remark:$desc,
                'ctime'         => $ctime
            ]);
            ManageLog::saveManageLog([
                'manage_id' => $manage_id_login,
                'desc'      => $desc,
                'content'   => ['manage_name' => $user_name, 'amount' => $money , 'balance' => $result_balance]
            ]);
            Db::commit();
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            $blog       = false;
            Db::rollback();
        }
        return $blog;

    }
}